package com.example.service1.provider.exception.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.service1.common.api.entity.ResponseResult;
import com.example.service1.common.api.entity.ServiceStateCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class GlobalBlockExceptionHandler implements BlockExceptionHandler {

    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        System.out.println("===========服务提供者===============");
        System.out.println("全局BlockException异常处理    服务熔断降级处理");
        response.setContentType("application/json; charset=utf-8");
        String json = objectMapper.writeValueAsString(ResponseResult.failure(ServiceStateCode.CURRENT_LIMITING));
        response.getWriter().write(json);
    }
}
